#include <iostream>
#include <vector>
#include <stack>
using namespace std;

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> v;
        if(root == nullptr)
            return v;

        stack<TreeNode*> st;
        TreeNode* node = root;
        while(!st.empty() || node !=nullptr){
            while(node != nullptr){
                v.push_back(node->val);
                st.push(node);
                node = node->left;
            }

            node = st.top();
            st.pop();
            node = node->right;
        }

        return v;
    }
};
